package com.qifei.xmlg_backend.controller;

import com.qifei.xmlg_backend.DTO.user.UserRegisterDTO;
import com.qifei.xmlg_backend.DTO.user.UserRequest;
import com.qifei.xmlg_backend.entity.Result;
import com.qifei.xmlg_backend.entity.User;
import com.qifei.xmlg_backend.service.IUserService;
import com.qifei.xmlg_backend.utils.Md5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 *
 * 用户
 *
 *
 * @author user
 * @since 2025-06-15
 */
@RestController
@RequestMapping("/users")
@RequiredArgsConstructor
@Api(tags = "用户管理接口")
public class UserController {

    private final IUserService userService;

    /**
     * 用户登录 */
    @PostMapping("/login")
    @ApiOperation(value = "用户登录", notes = "登录成功返回JWT令牌")
    public Result<?> login(@Valid @RequestBody UserRequest u){
        String token = userService.login(u);
        return Result.success(token);
    }

    /**
     * 获取用户信息
     * @return 用户信息（用户名、头像、角色列表）
     */
    @GetMapping("/info")
    @ApiOperation(value = "获取用户信息", notes = "从请求头获取token并返回用户名、头像和角色列表")
    public Result<?> getUserInfo(HttpServletRequest request) {
        // 从请求头获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            return Result.error("token不存在");
        }

        Map<String, Object> userInfo = userService.getUserInfo(token);
        return Result.success(userInfo);
    }

    /**
     * 用户注册
     * @param registerDTO 注册信息
     * @return 注册结果
     */
    @PostMapping("/register")
    @ApiOperation(value = "用户注册", notes = "注册成功返回用户信息（不含密码）")
    public Result<?> register(@Valid @RequestBody UserRegisterDTO registerDTO) {
        User user = userService.register(registerDTO);
        // 出于安全考虑，返回前清除密码
        user.setPassword(null);
        return Result.success(user);
    }
}